package hc.bre.policy

import hc.bre.cmn.RuleScriptBuilder

@groovy.transform.CompileStatic
class CheckBuilder extends RuleScriptBuilder<CheckDefinition>{
	@Override
	public Class buildClassRuleBodyResult_Class() {
		return CheckResult.class;
	}

	@Override
	public void buildClassRuleBodyCore() {
		apdNl("boolean _hited_ = false;")
		apdNl("boolean _hitToStop_ = false;")

		LinkedHashMap<CategoryOption,List<ReasonItem>> categroyMap = [:];

		ReasonDefinition reasonRuleDef = this.ruleOfReason;
		CategoryDefinition categoryRuleDef = this.ruleOfCategory;
		ruleDef.reasonBelongsTo.each { reasonId,categoryId->
			ReasonItem reason = reasonRuleDef.find(reasonId);
			CategoryOption category = categoryRuleDef.find(categoryId);

			List<ReasonItem> lst = categroyMap.get(category);

			if(lst == null) {
				lst = [];
				categroyMap.put(category, lst);
			}

			lst.add(reason);
		};

		categoryRuleDef.list.sort(true){ it.level };
		categoryRuleDef.list.each{ category ->
			List<ReasonItem> lst = categroyMap.get(category);

			if(!lst) return;

			apdNl("if(!(_hited_ && _hitToStop_)){");
			nested{
				String clazz = className(CheckResultReason.class)
				lst.each {
					apdNl("if({${it.script}}.call()){");
					indentInc();
					apdNl("_hited_ = true;");
					apdNl("${result}.reasonList.add(new ${clazz}(reason:${referRuleClass(reasonRuleDef)}.${it.code},category:${referRuleClass(categoryRuleDef)}.${category.code}));")
					
					indentDec();
					apdNl("};")
				}
			}
			apdNl("};");

			Boolean hitToStop = ruleDef.categoryHitToStop.get(category.id);
			apdNl("_hitToStop_ = ${hitToStop?true:false};");
			apdNl();
		};

		apdNl("${result}.reasonList = ${result}.reasonList.sort();")
		
		//categoryCode is the highest priority category code in list;
		apdNl("${result}.categoryCode = ${result}.reasonList?${result}.reasonList[0].categoryCode:'';")
		return;
	}

	void buildReasonOfCategory(CategoryOption category, List<ReasonItem> list) {
	}
}
